package com.joolun.weixin.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.joolun.common.constant.Constants;
import com.joolun.common.corp.TenantContext;
import com.joolun.common.enums.ErrorMsgEnum;
import com.joolun.common.exception.base.BaseException;
import com.joolun.common.utils.DateUtils;
import com.joolun.system.domain.*;
import com.joolun.system.mapper.ScrmStaffMapper;
import com.joolun.system.service.impl.SysCorpConfigServiceImpl;
import com.joolun.weixin.entity.StaffVO;
import com.joolun.weixin.service.IScrmCustomerService;
import com.joolun.weixin.config.WxCpConfiguration;
import com.joolun.weixin.service.*;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpExternalContactService;
import me.chanjar.weixin.cp.api.WxCpUserService;
import me.chanjar.weixin.cp.api.impl.WxCpExternalContactServiceImpl;
import me.chanjar.weixin.cp.api.impl.WxCpUserServiceImpl;
import me.chanjar.weixin.cp.bean.WxCpUser;
import me.chanjar.weixin.cp.bean.external.WxCpContactWayInfo;
import me.chanjar.weixin.cp.bean.external.WxCpContactWayResult;
import me.chanjar.weixin.cp.bean.user.WxCpDeptUserResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 企业微信成员Service业务层处理
 * 
 * @author joolun
 * @date 2025-02-25
 */
@Service
@Slf4j
public class ScrmStaffServiceImpl extends ServiceImpl<ScrmStaffMapper, ScrmStaff>  implements IScrmStaffService
{

    @Autowired
    private IScrmDepartmentService departmentService;
    @Autowired
    private IStaffDepartmentService staffDepartmentService;
    @Autowired
    private IScrmCustomerStaffService customerStaffService;
    @Autowired
    private IScrmCustomerInfoService customerInfoService;
    @Autowired
    private WxCpConfiguration wxCpConfiguration;
    @Autowired
    private SysCorpConfigServiceImpl sysCorpConfigService;

    /**
     * 查询企业微信成员
     * 
     * @param id 企业微信成员主键
     * @return 企业微信成员
     */
    @Override
    public ScrmStaff selectScrmStaffById(Long id)
    {
        return baseMapper.selectScrmStaffById(id);
    }

    /**
     * 查询企业微信成员列表
     * 
     * @param scrmStaff 企业微信成员
     * @return 企业微信成员
     */
    @Override
    public List<ScrmStaff> selectScrmStaffList(ScrmStaff scrmStaff)
    {
        scrmStaff.setExtCorpId(TenantContext.getTenantId());
        return baseMapper.selectScrmStaffList(scrmStaff);
    }

    /**
     * 新增企业微信成员
     * 
     * @param scrmStaff 企业微信成员
     * @return 结果
     */
    @Override
    @Transactional
    public int insertScrmStaff(ScrmStaff scrmStaff)
    {
        scrmStaff.setExtCorpId(TenantContext.getTenantId());
        scrmStaff.setCreateTime(DateUtils.getNowDate());

        List<ScrmDepartment> departments = new ArrayList<>();
        // 系统部门ID
        Long sysDeptId = scrmStaff.getSysDeptId();
        Long[] departIds = null;
        if (sysDeptId != null) {
            // 根据用户的平台部门id查询，企业部门信息
           // ScrmDepartment scrmDepartment = departmentService.getOne(Wrappers.lambdaQuery(ScrmDepartment.class).eq(ScrmDepartment::getSysDeptId,sysDeptId));
            //ScrmDepartment scrmDepartment = departmentService.checkExists(1L, "1");
           // scrmStaff.setExtCorpId(scrmDepartment.getExtCorpId());

           // departIds = JSON.parseArray("["+scrmDepartment.getExtCorpId()+"]", Long.class).toArray(new Long[0]);
            scrmStaff.setDeptIds(departIds.toString());
            //departments.add(scrmDepartment);
        }
        // 企业成员入库
        baseMapper.insertScrmStaff(scrmStaff);

        //2.处理员工-部门数据
        handlerDepartmentData(scrmStaff, departments, false);


//        //调用企业微信接口新增员工
//        WxCpUser wxCpUser = new WxCpUser();
//        BeanUtils.copyProperties(scrmStaff, wxCpUser);
//        wxCpUser.setUserId(scrmStaff.getExtId());
//        wxCpUser.setDepartIds(departIds);
//        // 企业通讯录
//        WxCpUserService userService = new WxCpUserServiceImpl(wxCpConfiguration.getAddressBookWxCpService());
//        try {
//            userService.create(wxCpUser);
//        } catch (WxErrorException e) {
//            log.error("---创建企业微信成员失败：{}",e.getMessage());
//            throw new RuntimeException(e);
//        }
        // 获取主体配置
        SysCorpConfig sysCorpConfig = sysCorpConfigService.getConfig(TenantContext.getTenantId());
        // 配置客户联系我
        WxCpExternalContactService externalContactService = new WxCpExternalContactServiceImpl(WxCpConfiguration.getWxCpService(sysCorpConfig));
        WxCpContactWayInfo wxCpContactWayInfo = new WxCpContactWayInfo();
        WxCpContactWayInfo.ContactWay contactWay = new WxCpContactWayInfo.ContactWay();
        contactWay.setType(WxCpContactWayInfo.TYPE.SINGLE);
        contactWay.setScene(WxCpContactWayInfo.SCENE.QRCODE);
        contactWay.setUsers(Lists.newArrayList(scrmStaff.getExtId()));
        contactWay.setRemark(scrmStaff.getRemark());
        wxCpContactWayInfo.setContactWay(contactWay);

        WxCpContactWayResult wxCpContactWayResult;
        try {
            wxCpContactWayResult =  externalContactService.addContactWay(wxCpContactWayInfo);
        } catch (WxErrorException e) {
            log.error("----配置客户联系我异常：{}",e.getMessage());
            throw BaseException.buildBaseException(e.getError(), "配置客户联系我异常");
        }
        // 更新二维码
        scrmStaff.setQrCodeUrl(wxCpContactWayResult.getQrCode());
        scrmStaff.setConfigId(wxCpContactWayResult.getConfigId());
        saveOrUpdate(scrmStaff);
        return 1;
    }

    /**
     * 修改企业微信成员
     * 
     * @param scrmStaff 企业微信成员
     * @return 结果
     */
    @Override
    public int updateScrmStaff(ScrmStaff scrmStaff)
    {
        scrmStaff.setUpdateTime(DateUtils.getNowDate());


        //校验参数
        ScrmStaff staffOld = getScrmStaffBySysUserId(scrmStaff.getSysUserId());
        if(staffOld == null){
            return 0;
        }
        // TODO：不为空的则为修改的属性
        staffOld.setName(scrmStaff.getName());

        List<ScrmDepartment> departments = new ArrayList<>();
        // 修改后的系统部门ID
        Long newSysDeptId = scrmStaff.getSysDeptId();

        // 判断部门ID是否变更
        Long[] departIds = null;
        if (null !=newSysDeptId && !staffOld.getSysDeptId().equals(newSysDeptId)) {
            // 根据旧的部门ID查找对应的企业微信部门ID信息
            ScrmDepartment newScrmDepartment = departmentService.getScrmDepartmentBySysDeptId(newSysDeptId);
            departIds = JSON.parseArray("["+newScrmDepartment.getExtId().toString()+"]", Long.class).toArray(new Long[0]);
            if(newScrmDepartment != null){
                departments.add(newScrmDepartment);
            }
        }


        //封装数据
//        ScrmStaff staff = new ScrmStaff();
//        BeanUtils.copyProperties(dto, staff);
//        staff.setCreatedAt(old.getCreatedAt())
//                .setUpdatedAt(new Date());

        //入库
        //1.修改成员
        baseMapper.updateScrmStaff(staffOld);

        //2.处理员工-部门数据
        handlerDepartmentData(staffOld, departments, true);


        //调用企业微信接口修改用户
        WxCpUser wxCpUser = new WxCpUser();
        BeanUtils.copyProperties(staffOld, wxCpUser);
        wxCpUser.setUserId(staffOld.getExtId());
        wxCpUser.setName(staffOld.getName());
        wxCpUser.setDepartIds(departIds);
        // 获取主体配置
        SysCorpConfig sysCorpConfig = sysCorpConfigService.getConfig(TenantContext.getTenantId());
        WxCpUserService userService = new WxCpUserServiceImpl(wxCpConfiguration.getAddressBookWxCpService(sysCorpConfig));
        try {
            userService.update(wxCpUser);
        } catch (WxErrorException e) {
            log.error("---更新企业微信成员:{}失败：{}",wxCpUser.getUserId(),e.getMessage());
            throw new RuntimeException(e);
        }

        return 1;
    }

    /**
     * 批量删除企业微信成员
     * 
     * @param ids 需要删除的企业微信成员主键
     * @return 结果
     */
    @Override
    public int deleteScrmStaffByIds(Long[] ids)
    {
        return baseMapper.deleteScrmStaffByIds(ids);
    }

    /**
     * 删除企业微信成员信息
     * 
     * @param id 企业微信成员主键
     * @return 结果
     */
    @Override
    public int deleteScrmStaffById(Long id)
    {
        return baseMapper.deleteScrmStaffById(id);
    }

    @Override
    public Boolean sync(String extCorpId) {
        log.info("开始同步企业id：[{}]的员工信息", extCorpId);
        Boolean syncRes = false;
        try {
            //先根据授权部门去同步
            syncRes = syncByDept(extCorpId);
        } catch (Exception e) {
            log.error("[{}]根据部门同步员工信息出错，", extCorpId, e);
        }
        //根据授权信息来同步
        //syncByAccredit(extCorpId);

        //刷新管理员
//        updateAdmin(extCorpId);
        return syncRes;
    }

    @Override
    public ScrmStaff checkExists(Long sysUserId) {
        if ( null == sysUserId) {
            return null;
        }
        ScrmStaff bySysUserId = getOne(Wrappers.lambdaQuery(ScrmStaff.class).eq(ScrmStaff::getSysUserId,sysUserId));
        if (bySysUserId == null) {
            throw new BaseException("企微员工不存在");
        }
        return bySysUserId;
    }

    @Override
    public ScrmStaff getScrmStaffBySysUserId(Long sysUserId){
        return  getOne(Wrappers.lambdaQuery(ScrmStaff.class).eq(ScrmStaff::getSysUserId,sysUserId));
    }


    private Boolean syncByDept(String extCorpId)throws WxErrorException  {

        if (StringUtils.isBlank(extCorpId)) {
            return true;
        }
        // 同步部门数据
        List<ScrmDepartment> departments = departmentService.sync(extCorpId);

        Map<String, Long> departExtIdStrAndIdMap = Optional.of(departments).orElse(new ArrayList<>()).stream()
                .collect(Collectors.toMap(o -> o.getExtId().toString(), ScrmDepartment::getId));
        try {
            // 获取主体配置
            SysCorpConfig sysCorpConfig = sysCorpConfigService.getConfig(TenantContext.getTenantId());
            // 同步员工数据
            WxCpUserService userService = new WxCpUserServiceImpl(wxCpConfiguration.getAddressBookWxCpService(sysCorpConfig));
            WxCpUserService userDetailService = new WxCpUserServiceImpl(wxCpConfiguration.getWxCpService(sysCorpConfig));
            // 获取成员ID列表 获取企业成员的userid与对应的部门ID列表
            WxCpDeptUserResult userListId = userService.getUserListId(null, 10000);
            Map<String, List<Long>> userDeptMap = userListId.getDeptUser().stream().collect(Collectors.groupingBy(WxCpDeptUserResult.DeptUserList::getUserId, Collectors.mapping(WxCpDeptUserResult.DeptUserList::getDepartment, Collectors.toList())));
            log.info("【同步员工】部门数量：{}，员工数量：{}", departments.size(), userListId.getDeptUser().size());

            // 微信用户信息
            List<WxCpUser> wxCpUsers = new ArrayList<>(userDeptMap.size());
            userDeptMap.forEach((u, d) -> {
                WxCpUser wxCpUser = new WxCpUser();
                wxCpUser.setUserId(u);
                wxCpUser.setName(u);
                wxCpUser.setDepartIds(d.toArray(new Long[0]));
                wxCpUsers.add(wxCpUser);
            });
            // 去除重复的数据
            Map<String, String> map = new HashMap<>();
            Iterator<WxCpUser> iterator = wxCpUsers.iterator();
            while (iterator.hasNext()) {
                WxCpUser next = iterator.next();
                if (StringUtils.isBlank(map.get(next.getUserId()))) {
                    map.put(next.getUserId(), next.getUserId());
                } else {
                    iterator.remove();
                }
            }

            List<Long> exitStaffIds = new ArrayList<>();
            if (CollectionUtil.isNotEmpty(wxCpUsers)) {
                wxCpUsers.forEach(user -> {
                    try {
                        List<StaffDepartment> staffDepartmentList = new ArrayList<>();

                        ScrmStaff staff = new ScrmStaff();
                        BeanUtils.copyProperties(user, staff);
                        staff.setAvatarUrl(user.getAvatar());
                        staff.setGender(user.getGender() == null ? "0" : user.getGender().getCode());

                        // 查询库里已有企业微信员工数据
                        ScrmStaff old = getOne(new QueryWrapper<ScrmStaff>().lambda().eq(ScrmStaff::getExtId, user.getUserId()).eq(ScrmStaff::getExtCorpId, extCorpId));
                        if (old != null) {
                            staff.setId(old.getId());
                            staff.setCreateBy(old.getCreateBy());
                            staff .setIsAdmin(old.getIsAdmin());
                        } else {
                            staff.setCreateTime(new Date());
                            // 保存员工
                            save(staff);
                        }
                        staff.setExtId(user.getUserId());
                        staff.setExtCorpId(extCorpId);
                        staff.setDeptIds(Arrays.toString(Optional.ofNullable(user.getDepartIds()).orElse(new Long[]{})));

                        AtomicInteger num = new AtomicInteger();
                        Arrays.asList(Optional.ofNullable(user.getDepartIds()).orElse(new Long[]{})).forEach(departId -> {

                            Integer[] isLeaderInDept = Optional.ofNullable(user.getIsLeaderInDept()).orElse(new Integer[]{});
                            StaffDepartment staffDepartment = new StaffDepartment();
                            log.info("---------------------企业微信员工ID---------------------------:{}",staff.getId()+"");
                            staffDepartment.setStaffId(staff.getId()+"");
                            staffDepartment.setExtStaffId(staff.getExtId().toString());
                            staffDepartment.setExtDepartmentId(departId);
                            staffDepartment.setDepartmentId(departExtIdStrAndIdMap.get(departId.toString())+"");
                            staffDepartment.setExtCorpId(extCorpId);
                            staffDepartment.setIsLeader(isLeaderInDept.length < num.get() + 1 ? null : user.getIsLeaderInDept()[num.get()])
//                                    .setOrder(user.getOrders()[num.get()])
                                    ;
                            num.set(num.get() + 1);
                            staffDepartmentList.add(staffDepartment);
                        });

                        WxCpUser userDetails = userDetailService.getById(staff.getExtId());
                        BeanUtils.copyProperties(userDetails, staff);
                        if (old != null) {
                            updateById(staff);
                            //删除旧的关联
                            staffDepartmentService.remove(new LambdaQueryWrapper<StaffDepartment>().eq(StaffDepartment::getStaffId, staff.getId()));
                        } else {
                            // 保存员工
                            updateById(staff);
                        }

                        exitStaffIds.add(staff.getId());
                        // 保存部门-员工的关联关系
                        staffDepartmentService.saveBatch(staffDepartmentList);

                    } catch (Exception e) {
                        log.error("同步员工信息失败，企业ID：【{}】,企业微信用户信息：【{}】,异常信息：【{}】", extCorpId, user.toJson(), e);
                    }

                });
            }
            // 删除不存在的员工
            List<ScrmStaff> staff = Optional.ofNullable(list(new LambdaQueryWrapper<ScrmStaff>().eq(ScrmStaff::getExtCorpId, extCorpId))).orElse(new ArrayList<>());
            Map<Long, ScrmStaff> staffIdAndStaffMap = staff.stream().collect(Collectors.toMap(ScrmStaff::getId, o -> o));
            List<Long> allIds = staff.stream().map(ScrmStaff::getId).collect(Collectors.toList());
            allIds.removeAll(exitStaffIds);

            // 对比后剩下的则为需要删除的员工ID
            if (CollectionUtil.isNotEmpty(allIds)) {
                staffDepartmentService.removeByStaffIds(allIds);
                removeByIds(allIds);
                List<ScrmStaff> staffList = allIds.stream().map(staffIdAndStaffMap::get).collect(Collectors.toList());
                log.info("删除用户列表：【{}】", allIds);
                //删除客户相关联系（删除员工-客户关联，员工-客户-详情，员工-客户标签）
                deleteCustomerAssociate(extCorpId, staffList);
            }
            // 更新部门人数
            Optional.ofNullable(departmentService.list()).orElse(new ArrayList<>()).forEach(department -> {
                Long staffNum = Optional.ofNullable(staffDepartmentService.queryDepartmentStaffNum(extCorpId, department.getExtId())).orElse(0L);
                department.setStaffNum(staffNum);
                departmentService.updateById(department);
            });


            //刷新员工客户数量
            Optional.ofNullable(customerStaffService.countGroupByStaffExtId(extCorpId)).orElse(new ArrayList<>()).forEach(countVO ->
                    update(new LambdaUpdateWrapper<ScrmStaff>().eq(ScrmStaff::getExtCorpId, extCorpId)
                            .eq(ScrmStaff::getExtId, countVO.getExtStaffId())
                            .set(ScrmStaff::getCustomerCount, Optional.ofNullable(countVO.getTotal()).orElse(0))));

        } catch (WxErrorException wx) {
            log.error("同步员工数据,调用企业微信接口异常：企业ID:【{}】,异常信息:【{}】", extCorpId, wx);
            throw new BaseException(ErrorMsgEnum.CODE_90001.getMsg());
        } catch (Exception e) {
            log.error("同步员工数据,系统异常：企业ID:【{}】,异常信息:【{}】", extCorpId, e);
            throw new BaseException(ErrorMsgEnum.CODE_90001.getMsg());
        }
        return true;
    }


    /**
     * 删除客户相关联系（删除员工-客户关联，员工-客户-详情，员工-客户标签）
     *
     * @param extCorpId
     * @param staffList
     */
    private void deleteCustomerAssociate(String extCorpId, List<ScrmStaff> staffList) {
        Date deleteAt = new Date();

        if (CollectionUtil.isEmpty(staffList)) {
            return;
        } else {
            staffList = staffList.stream().filter(Objects::nonNull).collect(Collectors.toList());
            if (CollectionUtil.isEmpty(staffList)) {
                return;
            }
        }
        List<String> staffExtIds = staffList.stream().map(ScrmStaff::getExtId).collect(Collectors.toList());

        if (CollectionUtil.isNotEmpty(staffExtIds)) {

            //员工-客户-详情
            customerInfoService.update(new LambdaUpdateWrapper<ScrmCustomerInfo>()
                    .eq(ScrmCustomerInfo::getExtCorpId, extCorpId)
                    .in(ScrmCustomerInfo::getExtStaffId, staffExtIds)
                    .set(ScrmCustomerInfo::getDeletedAt, deleteAt));
            customerInfoService.remove(new LambdaQueryWrapper<ScrmCustomerInfo>()
                    .eq(ScrmCustomerInfo::getExtCorpId, extCorpId)
                    .in(ScrmCustomerInfo::getExtStaffId, staffExtIds));

            //员工-客户标签
//            customerStaffTagService.update(new LambdaUpdateWrapper<WxCustomerStaffTag>()
//                    .eq(WxCustomerStaffTag::getExtCorpId, extCorpId)
//                    .in(WxCustomerStaffTag::getExtStaffId, staffExtIds)
//                    .set(WxCustomerStaffTag::getDeletedAt, deleteAt));
//            customerStaffTagService.remove(new LambdaQueryWrapper<WxCustomerStaffTag>()
//                    .eq(WxCustomerStaffTag::getExtCorpId, extCorpId)
//                    .in(WxCustomerStaffTag::getExtStaffId, staffExtIds));

            List<ScrmCustomerStaff> customerStaffs = customerStaffService.list(new LambdaQueryWrapper<ScrmCustomerStaff>()
                    .eq(ScrmCustomerStaff::getExtCorpId, extCorpId)
                    .in(ScrmCustomerStaff::getExtStaffId, staffExtIds));

            if (CollectionUtil.isNotEmpty(customerStaffs)) {
                List<Long> customerStaffIds = customerStaffs.stream().map(ScrmCustomerStaff::getId).collect(Collectors.toList());

                //删除员工-客户关联
                customerStaffService.update(new LambdaUpdateWrapper<ScrmCustomerStaff>()
                        .in(ScrmCustomerStaff::getId, customerStaffIds)
                        .set(ScrmCustomerStaff::getDeletedAt, deleteAt));
                customerStaffService.removeByIds(customerStaffIds);

                //如果这个客户跟进人小于1，则把这个客户移除
                List<String> extCustomerIds = customerStaffs.stream().map(ScrmCustomerStaff::getExtCustomerId).distinct().collect(Collectors.toList());
                Optional.of(extCustomerIds).orElse(new ArrayList<>()).forEach(extCustomerId -> {
                    if (OptionalLong.of(customerStaffService.count(new LambdaQueryWrapper<ScrmCustomerStaff>().eq(ScrmCustomerStaff::getExtCorpId, extCorpId)
                            .in(ScrmCustomerStaff::getExtCustomerId, extCustomerIds))).orElse(0) < 1) {
                        ScrmCustomerInfo customer = customerInfoService.checkExists(extCorpId, extCustomerId);
                        if (customer != null) {

                            customerInfoService.update(new LambdaUpdateWrapper<ScrmCustomerInfo>()
                                    .eq(ScrmCustomerInfo::getId, customer.getId())
                                    .set(ScrmCustomerInfo::getDeletedAt, deleteAt));
                            customerInfoService.removeById(customer.getId());
                        }

                    }
                });
            }
        }
    }


    private void handlerDepartmentData(ScrmStaff staff, List<ScrmDepartment> departments, boolean isUpdate) {

        // 如果为员工修改了部门，将之前所在部门数量减1操作,删除当前员工的关联数据
        if (isUpdate) {
//            List<String> departmentIds = Optional.ofNullable(staffDepartmentService.list(new LambdaQueryWrapper<StaffDepartment>()
//                    .select(StaffDepartment::getDepartmentId)
//                    .eq(StaffDepartment::getStaffId, staff.getId())
//            )).orElse(new ArrayList<>()).stream().map(StaffDepartment::getDepartmentId).collect(Collectors.toList());

            if (CollectionUtil.isNotEmpty(departments)) {
                ScrmDepartment department = departments.get(0);
                Long staffNum = department.getStaffNum();
                department.setStaffNum( staffNum -1);
                departmentService.updateById(department);
            }
            // 移除员工和部门关联关系
            staffDepartmentService.remove(new LambdaQueryWrapper<StaffDepartment>().eq(StaffDepartment::getStaffId, staff.getId()));
        }

        // 新增用户数据关联
        if (CollectionUtil.isNotEmpty(departments)) {
            List<StaffDepartment> staffDepartmentList = new ArrayList<>();
            List<ScrmDepartment> departmentList = new ArrayList<>();
            departments.forEach(department -> {
                        staffDepartmentList.add(new StaffDepartment().setExtCorpId(staff.getExtCorpId())
                                .setStaffId(staff.getId()+"")
                                .setIsLeader(0)
                                .setDepartmentId(department.getExtId()+"")
                                .setExtDepartmentId(department.getExtId())
                                .setExtStaffId(staff.getExtId())
                        );
                        // 更新部门人数
                        department.setStaffNum(department.getStaffNum()+1);
                        departmentList.add(department);
                    }

            );
            staffDepartmentService.saveBatch(staffDepartmentList);
            departmentService.updateBatchById(departmentList);
        }


    }

    public StaffVO translation(ScrmStaff staff) {
        StaffVO vo = new StaffVO();
        if (staff != null) {
            BeanUtils.copyProperties(staff, vo);
            List<String> departmentIds = Optional.ofNullable(staffDepartmentService.list(new LambdaQueryWrapper<StaffDepartment>().eq(StaffDepartment::getStaffId, staff.getId())))
                    .orElse(new ArrayList<>()).stream().map(StaffDepartment::getDepartmentId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(departmentIds)) {
                List<ScrmDepartment> departments = Optional.ofNullable(departmentService.listByIds(departmentIds)).orElse(new ArrayList<>());
                departments.sort(Comparator.comparingLong(ScrmDepartment::getOrder).reversed());
                vo.setDepartmentList(departments);
            } else {
                vo.setDepartmentList(Collections.singletonList(departmentService.getRootDepartment(staff.getExtCorpId())));
            }
        }
        return vo;
    }

    @Override
    public List<String> getAllExtId(String extCorpId) {
        return list(new QueryWrapper<ScrmStaff>().lambda()
                .select(ScrmStaff::getExtId)
                .eq(ScrmStaff::getExtCorpId, extCorpId))
                .stream().map(ScrmStaff::getExtId).collect(Collectors.toList());
    }

    @Override
    public List<String> getStaffIdsByDepts(String corpId, List<Long> departmentIds, List<String> staffIds) {
        List<String> staffIdList = new ArrayList<>();
        //选择了根部门，查所有员工
        if (CollectionUtil.isNotEmpty(departmentIds) && departmentIds.contains(Constants.SYS_ROOT_DEPARTMENT)) {
            return Optional.ofNullable(list(new QueryWrapper<ScrmStaff>().lambda()
                            .select(ScrmStaff::getExtId)
                            .eq(ScrmStaff::getExtCorpId, corpId))).orElse(new ArrayList<>()).stream().map(ScrmStaff::getExtId)
                    .collect(Collectors.toList());
        }

        if (CollectionUtil.isNotEmpty(staffIds)) {
            staffIdList.addAll(staffIds);
        }

        //根据部门筛选当前及所有子部门员工id
        if (CollectionUtil.isNotEmpty(departmentIds)) {
            List<Long> childIdList = departmentService.getChildIdList(corpId, departmentIds);
            List<String> staffIdsByDept = Optional.ofNullable(staffDepartmentService.list(new LambdaQueryWrapper<StaffDepartment>()
                            .in(StaffDepartment::getExtDepartmentId, childIdList)
                            .eq(StaffDepartment::getExtCorpId, corpId)))
                    .orElse(new ArrayList<>()).stream().map(StaffDepartment::getExtStaffId).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(staffIdsByDept)) {
                staffIdList.addAll(staffIdsByDept);
            }
        }
        return staffIdList.stream().distinct().collect(Collectors.toList());
    }


}
